package cn.xtits.xtp.controller;

import cn.xtits.xtf.common.utils.JsonUtil;
import cn.xtits.xtf.common.web.AjaxResult;
import cn.xtits.xtf.common.web.Pagination;
import cn.xtits.xtp.entity.CodingRule;
import cn.xtits.xtp.entity.Supplier;
import cn.xtits.xtp.entity.SupplierExample;
import cn.xtits.xtp.enums.CodingRuleEnum;
import cn.xtits.xtp.enums.CodingRuleTypeEnum;
import cn.xtits.xtp.service.CodingRuleService;
import cn.xtits.xtp.service.SupplierService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @fileName: SupplierController.java
 * @author: Dan
 * @createDate: 2018-02-28 13:43:14
 * @description: 供应商
 */
@RestController
@RequestMapping("/supplier")
public class SupplierController extends BaseController {

    @Autowired
    private SupplierService service;

    @Autowired
    private CodingRuleService codingRuleService;

    @RequiresPermissions("ibasic-supplier:insert")
    @RequestMapping(value = "insertSupplier")
    public AjaxResult insertSupplier(
            @RequestParam(value = "data", required = false) String data) {
        Supplier record = JsonUtil.fromJson(data, Supplier.class);
        //record.setCode(getCode());
        if (exist(record) > 0) {
            return new AjaxResult(-2, "存在相同的编码或名称!");
        }
        //Date dt = getDateNow();
        record.setCreateDate(null);
        record.setMakeBillMan(getUserName());
        record.setModifier(getUserName());
        record.setModifyDate(null);
        record.setDeleteFlag(false);
        service.insert(record);
        return new AjaxResult(record);
    }

    @RequiresPermissions("ibasic-supplier:delete")
    @RequestMapping(value = "deleteSupplier")
    public AjaxResult deleteSupplier(
            @RequestParam(value = "id", required = false) int id) {
        Supplier record = new Supplier();
        record.setId(id);
        record.setDeleteFlag(true);
        record.setModifier(getUserName());
        record.setModifyDate(null);
        int row = service.updateByPrimaryKeySelective(record);
        return new AjaxResult(row);
    }

    @RequiresPermissions("ibasic-supplier:update")
    @RequestMapping(value = "updateSupplier")
    public AjaxResult updateSupplier(
            @RequestParam(value = "data", required = false) String data) {
        Supplier record = JsonUtil.fromJson(data, Supplier.class);
        if (exist(record) > 0) {
            return new AjaxResult(-2, "存在相同的编码或名称!");
        }
        record.setCreateDate(null);
        record.setMakeBillMan(null);
        record.setModifyDate(null);
        record.setModifier(getUserName());
        record.setDeleteFlag(false);
        service.updateByPrimaryKeySelective(record);
        return new AjaxResult(record);
    }

    @RequestMapping(value = "listSupplier")
    public AjaxResult listSupplier(
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "shortName", required = false) String shortName,
            @RequestParam(value = "director", required = false) String director,
            @RequestParam(value = "tel", required = false) String tel,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "taxId", required = false) String taxId,
            @RequestParam(value = "mail", required = false) String mail,
            @RequestParam(value = "site", required = false) String site,
            @RequestParam(value = "fax", required = false) String fax,
            @RequestParam(value = "depositBank", required = false) String depositBank,
            @RequestParam(value = "bankAccount", required = false) String bankAccount,
            @RequestParam(value = "credit", required = false) String credit,
            @RequestParam(value = "remark", required = false) String remark,
            @RequestParam(value = "pageSize", required = false) Integer pageSize,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        SupplierExample example = new SupplierExample();
        example.setPageIndex(pageIndex);
        example.setPageSize(pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            example.setOrderByClause(orderBy);
        }
        SupplierExample.Criteria criteria = example.createCriteria();

        criteria.andDeleteFlagEqualTo(false);
        if (StringUtils.isNotBlank(id)) {
            String[] split = id.split(",");
            if (split.length > 1) {
                List<Integer> idList = new ArrayList<>();
                for (String s : split) {
                    idList.add(Integer.parseInt(s));
                }
                criteria.andIdIn(idList);
            } else {
                criteria.andIdEqualTo(Integer.parseInt(split[0]));
            }
        }
        if (StringUtils.isNotBlank(code)) {
            criteria.andCodeLike(code);
        }
        if (StringUtils.isNotBlank(name)) {
            criteria.andNameLike(name);
        }
        if (StringUtils.isNotBlank(shortName)) {
            criteria.andShortNameLike(shortName);
        }
        if (StringUtils.isNotBlank(director)) {
            criteria.andDirectorLike(director);
        }
        if (StringUtils.isNotBlank(tel)) {
            criteria.andTelLike(tel);
        }
        if (StringUtils.isNotBlank(phone)) {
            criteria.andPhoneLike(phone);
        }
        if (StringUtils.isNotBlank(address)) {
            criteria.andAddressLike(address);
        }
        if (StringUtils.isNotBlank(taxId)) {
            criteria.andTaxIdLike(taxId);
        }
        if (StringUtils.isNotBlank(mail)) {
            criteria.andMailLike(mail);
        }
        if (StringUtils.isNotBlank(site)) {
            criteria.andSiteLike(site);
        }
        if (StringUtils.isNotBlank(fax)) {
            criteria.andFaxLike(fax);
        }
        if (StringUtils.isNotBlank(depositBank)) {
            criteria.andDepositBankLike(depositBank);
        }
        if (StringUtils.isNotBlank(bankAccount)) {
            criteria.andBankAccountLike(bankAccount);
        }
        if (StringUtils.isNotBlank(credit)) {
            criteria.andCreditLike(credit);
        }
        if (StringUtils.isNotBlank(remark)) {
            criteria.andRemarkLike(remark);
        }
        if (StringUtils.isNotBlank(startDate)) {
            criteria.andCreateDateGreaterThanOrEqualTo(DateTime.parse(startDate, format).toDate());
        }
        if (StringUtils.isNotBlank(endDate)) {

            criteria.andCreateDateLessThanOrEqualTo(DateTime.parse(endDate, format).toDate());
        }

        List<Supplier> list = service.listByExample(example);
        Pagination<Supplier> pList = new Pagination<>(example, list, example.getCount());
        return new AjaxResult(pList);
    }

    @RequestMapping(value = "getSupplier")
    public AjaxResult getSupplier(@RequestParam(value = "id", required = false) Integer id) {
        Supplier res = service.getByPrimaryKey(id);
        return new AjaxResult(res);
    }

    private String getCode() {
        Map<String, Object> assemblyCodingMap = codingRuleService.getAssemblyCoding(CodingRuleEnum.SUPPLIER_CODE.key);
        StringBuffer codeBuffer = new StringBuffer();
        //固定字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.FIXED_FIELD.key)) {
            codeBuffer.append(assemblyCodingMap.get(CodingRuleTypeEnum.FIXED_FIELD.key).toString());
        }
        //时间字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.DATE_FIELD.key)) {
            codeBuffer.append(DateTime.now().toString(assemblyCodingMap.get(CodingRuleTypeEnum.DATE_FIELD.key).toString()));
        }
        CodingRule codingRule = null;
        //自增字段
        if (assemblyCodingMap.containsKey(CodingRuleTypeEnum.IDENTITY_FIELD.key)) {
            codingRule = (CodingRule) assemblyCodingMap.get(CodingRuleTypeEnum.IDENTITY_FIELD.key);
        }
        String codeLike = codeBuffer.toString();
        SupplierExample example = new SupplierExample();
        example.setPageSize(1);
        example.setOrderByClause("Code desc, Id desc");
        SupplierExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andCodeLike(codeLike + "%");
        List<Supplier> supplierList = service.listByExample(example);
        if (codingRule != null) {
            int length = codingRule.getLength() == null ? 4 : codingRule.getLength();
            long initValue = Long.parseLong(codingRule.getInitValue() == null ? "1" : codingRule.getInitValue());
            if (supplierList.size() > 0) {
                String code = supplierList.get(0).getCode();
                String substring = code.substring(codeLike.length(), code.length());
                initValue = Long.parseLong(substring) + 1;
            }
            String format = String.format("%0" + length + "d", initValue);
            return codeLike + format;
        }
        return codeLike;
    }

    private int exist(Supplier record) {
        {
            SupplierExample example = new SupplierExample();
            SupplierExample.Criteria criteria = example.createCriteria();
            criteria.andDeleteFlagEqualTo(false);
            if (record.getId() != null && record.getId() > 0) {
                criteria.andIdNotEqualTo(record.getId());
            }
            criteria.andCodeEqualTo(record.getCode());
            List<Supplier> list = service.listByExample(example);
            if (list.size() > 0) {
                return list.size();
            }
        }
        SupplierExample example = new SupplierExample();
        SupplierExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(false);
        if (record.getId() != null && record.getId() > 0) {
            criteria.andIdNotEqualTo(record.getId());
        }
        criteria.andNameEqualTo(record.getName());
        List<Supplier> list = service.listByExample(example);

        return list.size();

    }
}